import 'dart:convert';
import 'dart:math';

import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class WhlExploreLogic extends GetxController {
  List<WhlProductBean> productList = [];
  List<String> typeList = ['All', 'Short', 'Hilarious', 'Funny'];
  int selectedIndex = 0;

  onGetProductList() async {
    List<WhlProductBean>? result = [];
    if (selectedIndex == 0) {
      result = await WhlDBUtils().productDao.findAllProducts();
    } else {
      result = await WhlDBUtils().productDao.findProductByType(typeList[selectedIndex]);
    }
    if (result != null && result.isNotEmpty) {
      productList = result;
      update();
      return;
    }
    String json = await rootBundle.loadString("assets/json/data.json");
    List dataMap = jsonDecode(json);
    print(dataMap);
    Map<String, dynamic> params = {
      "category": "Popular",
      "isPageMode": true,
      "isRemoteImageUrl": true,
      "limit": 20,
      "page": 1,
      "tag": "All",
    };
    // ResponseData responseData = await WhlApi.getWall.post(params);
    // if (responseData.isSuccess()) {
    //   List list = responseData.data;
    //   List<WhlProductBean> modelList = list.map((e) => WhlProductBean.fromJson(e)).toList();
    //   List<WhlProductBean> tempList = [];
    //   for (var element in dataMap) {
    //     int index = dataMap.indexOf(element);
    //     WhlProductBean model = modelList[index];
    //     List productList = element['product'];
    //     for (var element in productList) {
    //       model.title = element['title'];
    //       model.describe = element['describe'];
    //       model.type = element['type'];
    //       model.cover = element['cover'];
    //       model.details = (element['details'] as List).map((e) => e.toString()).toList();
    //       model.likeNum = Random().nextInt(20);
    //       model.isLike = false;
    //       model.isFollowed = false;
    //       model.followNum = Random().nextInt(20);
    //       tempList.add(model);
    //       WhlDBUtils().productDao.insertProduct(model);
    //     }
    //   }
    //   productList = tempList;
    //   update();
    // }
  }

  doClickType(index) {
    selectedIndex = index;
    update();
    onGetProductList();
  }

  doClickLike(WhlProductBean model) {
    model.isLike = !model.isLike!;
    model.likeNum = (model.likeNum ?? 0) + (model.isLike! ? 1 : -1);
    update();
    WhlDBUtils().productDao.updateProduct(model);
  }

  doClickItem(WhlProductBean model) {
    Get.toNamed(Routes.productDetail, arguments: model);
  }
}
